/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FilterDialog.java
 *
 * Created on 28 Mei 11, 1:43:41
 */
package log2excel;

import com.toedter.calendar.JCalendar;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTable;
import javax.swing.SpinnerNumberModel;
import javax.swing.table.DefaultTableModel;
import log2excel.ViewInterface.TableAccess;
import log2excel.model.ExtentionUsernameRecord;
import log2excel.model.TrunkLineRecord;

/**
 *
 * @author aegish
 */
public class FilterDialog extends javax.swing.JDialog {
    public static enum Option{
      ExtentionUsername,
      TrunkLine
    };
    private Option option;
//    public Date Start;
//    public Date End;
//    public Date timeStart;
//    public Date timeEnd;
    public long start;
    public long end;
    public long Duration;
    public ArrayList selected;
    public boolean canceled = true;
    
    /** Creates new form FilterDialog */
    public FilterDialog(java.awt.Frame parent, boolean modal,Option option) {
        super(parent, modal);
        initComponents();
        prepareFilterItem();
        this.option = option;
        prepareTable(option);
        timeFilterCheckBox.setText("Call Made Between");
        if (option == FilterDialog.Option.ExtentionUsername){
            tableLabel.setText("Extention / Username Select All");
        }
        else {
            tableLabel.setText("Trunk / Line  Select All");
        }
        nextButton.setText("next");
        cancelButton.setText("cancel");
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        timeFilterCheckBox = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        cancelButton = new javax.swing.JButton();
        nextButton = new javax.swing.JButton();
        tableLabel = new javax.swing.JCheckBox();
        tablePanel = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        jPanel1.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        jPanel1.setEnabled(false);
        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 450, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 237, Short.MAX_VALUE)
        );

        timeFilterCheckBox.setSelected(true);
        timeFilterCheckBox.setName("timeFilterCheckBox"); // NOI18N
        timeFilterCheckBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                timeFilterCheckBoxItemStateChanged(evt);
            }
        });

        jPanel2.setName("jPanel2"); // NOI18N

        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        nextButton.setName("nextButton"); // NOI18N
        nextButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(nextButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nextButton)
                    .addComponent(cancelButton))
                .addGap(32, 32, 32))
        );

        tableLabel.setName("tableLabel"); // NOI18N
        tableLabel.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tableLabelItemStateChanged(evt);
            }
        });

        tablePanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        tablePanel.setName("tablePanel"); // NOI18N

        javax.swing.GroupLayout tablePanelLayout = new javax.swing.GroupLayout(tablePanel);
        tablePanel.setLayout(tablePanelLayout);
        tablePanelLayout.setHorizontalGroup(
            tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 450, Short.MAX_VALUE)
        );
        tablePanelLayout.setVerticalGroup(
            tablePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 138, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tableLabel)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(timeFilterCheckBox)
                        .addGap(284, 284, 284))
                    .addComponent(tablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(timeFilterCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tableLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(tablePanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nextButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextButtonActionPerformed
        // TODO add your handling code here:
        canceled = false;
        if (timeFilterCheckBox.isSelected()){
            System.out.println("selected");
            Date starttime = calstart.getDate();
            starttime.setHours(Integer.parseInt(hourstart.getValue().toString()));
            starttime.setMinutes(Integer.parseInt(minutestart.getValue().toString()));
            starttime.setSeconds(Integer.parseInt(secondstart.getValue().toString()));
            Date endtime = calend.getDate();
            endtime.setHours(Integer.parseInt(hourend.getValue().toString()));
            endtime.setMinutes(Integer.parseInt(minuteend.getValue().toString()));
            endtime.setSeconds(Integer.parseInt(secondend.getValue().toString()));
            start = starttime.getTime();
            end  = endtime.getTime();
            System.out.println(start);
            System.out.println(end);
            Duration = Long.parseLong(duration.getValue().toString());
        }
        else {
            System.out.println("not selected");
            start = 0;
            end = 0;
            Duration = 0;
        }
        getselecteditem();
        setVisible(false);
    }//GEN-LAST:event_nextButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
//        canceled = true;
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void timeFilterCheckBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_timeFilterCheckBoxItemStateChanged
        // TODO add your handling code here:
        if (evt.getStateChange() == ItemEvent.DESELECTED){
            Component[] components = jPanel1.getComponents();
            for (int i = 0; i < components.length; i++) {
                Component component = components[i];
                component.setEnabled(false);
            }
        }
        else{
            Component[] components = jPanel1.getComponents();
            for (int i = 0; i < components.length; i++) {
                Component component = components[i];
                component.setEnabled(true);
            }
        }
    }//GEN-LAST:event_timeFilterCheckBoxItemStateChanged

    private void tableLabelItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tableLabelItemStateChanged
        if (evt.getStateChange() == ItemEvent.SELECTED){
            Component[] components = tablePanel.getComponents();
            for (int i = 0; i < components.length; i++) {
                Component component = components[i];
                component.setEnabled(false);
            }
        }
        else{
            Component[] components = tablePanel.getComponents();
            for (int i = 0; i < components.length; i++) {
                Component component = components[i];
                component.setEnabled(true);
            }
        }
    }//GEN-LAST:event_tableLabelItemStateChanged

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                FilterDialog dialog = new FilterDialog(new javax.swing.JFrame(), true, Option.ExtentionUsername);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JButton nextButton;
    private javax.swing.JCheckBox tableLabel;
    private javax.swing.JPanel tablePanel;
    private javax.swing.JCheckBox timeFilterCheckBox;
    // End of variables declaration//GEN-END:variables

    private JCalendar calstart = new JCalendar(new Date());
    private JCalendar calend = new JCalendar(new Date());
    private JSpinner hourstart = new JSpinner(new SpinnerNumberModel(0, 0, 23, 1));
    private JSpinner minutestart = new JSpinner(new SpinnerNumberModel(0, 0, 59, 1));
    private JSpinner secondstart = new JSpinner(new SpinnerNumberModel(0, 0, 59, 1));
    private JSpinner hourend = new JSpinner(new SpinnerNumberModel(0, 0, 23, 1));
    private JSpinner minuteend = new JSpinner(new SpinnerNumberModel(0, 0, 59, 1));
    private JSpinner secondend = new JSpinner(new SpinnerNumberModel(0, 0, 59, 1));
    private JSpinner duration = new JSpinner(new SpinnerNumberModel(0, 0, Integer.MAX_VALUE, 1));
    private JTable table0;
    private JTable table1;
    private void prepareFilterItem() {
        JLabel dateLabel = new JLabel("Date");
        calstart.setMaximumSize(new Dimension(100, 100));
        calend.setMaximumSize(new Dimension(100, 100));
        JLabel sd = new JLabel("  sd  ");
        JLabel sd1 = new JLabel("  sd  ");
        JLabel timeLabel = new JLabel("Time");
        JLabel hourLabel = new JLabel("Hour:");
        JLabel minuteLable = new JLabel("  Minute:");
        JLabel secondLable = new JLabel("  Second:");
        JLabel hourLabel1 = new JLabel("Hour:");
        JLabel minuteLable1 = new JLabel("  Minute:");
        JLabel secondLable1 = new JLabel("  Second:");
        JLabel durationLabel = new JLabel("Duration");
        JLabel secLabel = new JLabel("sec");
        duration.setMaximumSize(new Dimension(20, 5));
        GroupLayout layout = new GroupLayout(jPanel1);
        layout.setAutoCreateGaps(true);
        layout.setAutoCreateContainerGaps(true);
        
        layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(dateLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(calstart)
                        .addComponent(sd)
                        .addComponent(calend)
                    )
                    .addComponent(timeLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(hourLabel)
                        .addComponent(hourstart)
                        .addComponent(minuteLable)
                        .addComponent(minutestart)
                        .addComponent(secondLable)
                        .addComponent(secondstart)
                        .addComponent(sd1)
                        .addComponent(hourLabel1)
                        .addComponent(hourend)
                        .addComponent(minuteLable1)
                        .addComponent(minuteend)
                        .addComponent(secondLable1)
                        .addComponent(secondend)
                    )
                    .addComponent(durationLabel)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(duration)
                        .addComponent(secLabel)
                    )
                )
            );
        layout.setVerticalGroup(layout.createSequentialGroup()
                .addComponent(dateLabel)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(calstart)
                    .addComponent(sd)
                    .addComponent(calend)
                )
                .addComponent(timeLabel)
                .addGroup(layout.createParallelGroup()
                    .addComponent(hourLabel)
                    .addComponent(hourstart)
                    .addComponent(minuteLable)
                    .addComponent(minutestart)
                    .addComponent(secondLable)
                    .addComponent(secondstart)
                    .addComponent(sd1)
                    .addComponent(hourLabel1)
                    .addComponent(hourend)
                    .addComponent(minuteLable1)
                    .addComponent(minuteend)
                    .addComponent(secondLable1)
                    .addComponent(secondend)
                )
                .addComponent(durationLabel)
                .addGroup(layout.createParallelGroup()
                    .addComponent(duration)
                    .addComponent(secLabel)
                )
            );
        jPanel1.setLayout(layout);
        this.setSize(600, 600);
        this.setResizable(false);
    }
    private void prepareTable(Option opt){
        if (opt == Option.ExtentionUsername){
            table0 = new JTable(new DefaultTableModel(new Object[][]{
            }, new String[]{"Extention", "Username"}){
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
            DefaultTableModel model = (DefaultTableModel)table0.getModel();
            ArrayList<ExtentionUsernameRecord> arraylist = TableAccess.getExtentionUsernameRecords();
            for (int i = 0; i < arraylist.size(); i++){
                model.addRow(arraylist.get(i).toArray());
            }
            table1 = new JTable(new DefaultTableModel(new Object[][]{
            }, new String[]{"Extention", "Username"}){
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
        } else {
            table0 = new JTable(new DefaultTableModel(new Object[][]{
            }, new String[]{"Trunk", "Line"}){
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
            DefaultTableModel model = (DefaultTableModel)table0.getModel();
            ArrayList<TrunkLineRecord> arraylist = TableAccess.getTrunkLineRecords();
            for (int i = 0; i < arraylist.size(); i++){
                model.addRow(arraylist.get(i).toArray());
            }
            table1 = new JTable(new DefaultTableModel(new Object[][]{
            }, new String[]{"Trunk", "Line"}){
                @Override
                public boolean isCellEditable(int row, int column) {
                    return false;
                }
            });
        }
        
        JScrollPane scrollPane0 = new JScrollPane(table0);
        scrollPane0.setSize(table0.getPreferredSize());
        JLabel selectedtable = new JLabel("Selected");
        JLabel deselectedtable = new JLabel("Deselected");
        JScrollPane scrollPane1 = new JScrollPane(table1);
        scrollPane1.setSize(table1.getPreferredSize());
        JButton add = new JButton("<<<");
        JButton rem = new JButton(">>>");
        add.setSize(5,5);
        rem.setSize(5,5);
        GroupLayout layout = new GroupLayout(tablePanel);
        layout.setHorizontalGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(selectedtable)
                    .addComponent(scrollPane0))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                    .addComponent(add)
                    .addComponent(rem))
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(deselectedtable)
                    .addComponent(scrollPane1)));
        layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(selectedtable)
                    .addComponent(scrollPane0))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(add)
                    .addComponent(rem))
                .addGroup(layout.createSequentialGroup()
                    .addComponent(deselectedtable)
                    .addComponent(scrollPane1)));
        tablePanel.setLayout(layout);
        add.addActionListener(addActionListener);
        rem.addActionListener(remActionListener);
    }
    private ActionListener remActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int[] selectedrows = table0.getSelectedRows();
            for (int i = 0; i < selectedrows.length; i++) {
                int j = selectedrows[i];
                Object ext = table0.getValueAt(j, 0);
                Object name = table0.getValueAt(j, 1);
                DefaultTableModel model = (DefaultTableModel) table1.getModel();
                model.addRow(new Object[]{ext,name});
            }
            for (int i = selectedrows.length - 1; i >= 0; i--) {
                ((DefaultTableModel)table0.getModel()).removeRow(selectedrows[i]);
            }
        }
    };
    private ActionListener addActionListener = new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int[] selectedrows = table1.getSelectedRows();
            for (int i = 0; i < selectedrows.length; i++) {
                int j = selectedrows[i];
                Object ext = table1.getValueAt(j, 0);
                Object name = table1.getValueAt(j, 1);
                DefaultTableModel model = (DefaultTableModel) table0.getModel();
                model.addRow(new Object[]{ext,name});
            }
            for (int i = selectedrows.length - 1; i >= 0; i--) {
                ((DefaultTableModel)table1.getModel()).removeRow(selectedrows[i]);
            }
        }
    };
    private void getselecteditem(){
        DefaultTableModel model = (DefaultTableModel) table0.getModel();
        if (option == Option.ExtentionUsername){
            selected = new ArrayList<ExtentionUsernameRecord>();
            int row = model.getRowCount();
            for (int i = 0; i < row; i++){
                String ext = model.getValueAt(i, 0) != null ? model.getValueAt(i, 0).toString() : "";
                String username = model.getValueAt(i, 1) != null ? model.getValueAt(i, 1).toString() : "";
                ExtentionUsernameRecord eur = new ExtentionUsernameRecord(ext, username);
                selected.add(eur);
            }
        } else{
            selected = new ArrayList<TrunkLineRecord>();
            int row = model.getRowCount();
            for (int i = 0; i < row; i++){
                String trunk = model.getValueAt(i, 0) != null ? model.getValueAt(i, 0).toString() : "";
                String line = model.getValueAt(i, 1) != null ? model.getValueAt(i, 1).toString() : "";
                TrunkLineRecord eur = new TrunkLineRecord(trunk, line);
                selected.add(eur);
            }
        }
    }
}
